package cluster

import (
	"net"
	"gitee.com/cooge/impush/core"
	"errors"
	"gitee.com/cooge/impush/cluster/conn"
	"gitee.com/cooge/impush/message"
	"encoding/json"
	log "github.com/sirupsen/logrus"
)




type ClusterServer struct {
	listener *net.TCPListener
}

func NewClusterServer() *ClusterServer {
	var cs ClusterServer
	return &cs
}
func (this *ClusterServer) Bind(lport int) error {
	conn, err := net.ListenTCP("tcp4", &net.TCPAddr{
		IP:   net.IPv4(0, 0, 0, 0),
		Port: lport,
	})
	if err == nil {
		core.AddInfo("CLUSTER_LOCAL_PORT", lport)
		this.listener = conn
	}
	return err
}
func (this *ClusterServer) Accept() (*conn.ClusterConn, error) {
	if this.listener != nil {
		tcn, err := this.listener.Accept()
		if err == nil {
			nt, ok := tcn.(*net.TCPConn)
			if ok {
				return conn.NewClusterConn(nt,deleteUserHandlerFunc,addUserHandlerFunc,netBreakHandlerFunc,noUserHandlerFunc), nil
			} else {
				return nil, errors.New("CLUSTER TCP ERROR")
			}
		} else {
			return nil, err
		}
	}
	return nil, errors.New("SYS CLUSTER TCP ERROR")
}

func netBreakHandlerFunc(conn *conn.ClusterConn)  {
	deleteClusterConnUser(conn)
}
func noUserHandlerFunc(userid string,conn *conn.ClusterConn)  {
	deleteClusterConnUserId(userid,conn)
}


func deleteUserHandlerFunc(conn *conn.ClusterConn,msg *message.Message)  {
	data:=msg.Body
	if len(data)>0{
		var cus []clusterUser
		err:=json.Unmarshal(data,&cus)
		if err==nil{
			for _,v:=range cus{
				ncc:=NewClusterConnUser(conn,v.Time)
				deleteClusterUser(v.UserId,ncc)
			}
		}else{
			log.Debug("批量用户发送转换失败",err)
		}
	}
}

func addUserHandlerFunc(conn *conn.ClusterConn,msg *message.Message)  {
	data:=msg.Body
	if len(data)>0{
		var cus []clusterUser
		err:=json.Unmarshal(data,&cus)
		if err==nil{
			for _,v:=range cus{
				ncc:=NewClusterConnUser(conn,v.Time)
				addClusterUser(v.UserId,ncc)
			}
		}else{
			log.Debug("批量用户发送转换失败",err)
		}
	}
}